<?php

namespace App\Admin\Controllers;

use App\Models\StoreApply;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;




class StoreApplyController extends VuePageController
{
    /**
     * 门店申请列表
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $content = $this->vue($content);
        return $content
            ->title('门店申请管理')
            ->description('门店申请列表')
            ->body(view('admin.store_apply.applications'));
    }

    /**
     * 列表接口：供前端 Vue 请求
     */
    public function list(Request $request)
    {
        $page = max(1, (int) $request->input('page', 1));
        $pageSize = max(1, min(50, (int) $request->input('pageSize', 10)));

        $query = StoreApply::with('member')
            ->where('status', '!=', -1)
            ->where('uniacid', '1')
            ->orderBy('created_at', 'desc');

        if ($request->filled('applicant_id')) {
            $query->where('id', $request->applicant_id);
        }
        if ($request->filled('realname')) {
            $query->where('realname', 'like', '%'.$request->realname.'%');
        }
        if ($request->filled('store_name')) {
            $keyword = $request->store_name;
            $escapedKeywordUpper = $this->convertToUnicodeEscape($keyword); // 默认返回大写
            $escapedKeywordLower = strtolower($escapedKeywordUpper);
            $query->where(function ($subQuery) use ($keyword, $escapedKeywordUpper, $escapedKeywordLower) {
                // 兼容 JSON 文本存储，使用模糊匹配（包含中文与 Unicode 转义两种形式，兼容大小写）
                $subQuery->where('information', 'like', '%"store_name":"%'.$keyword.'%')
                    ->orWhere('information', 'like', $escapedKeywordUpper)
                    ->orWhere('information', 'like', $escapedKeywordLower)
                    ->orWhere('information', 'like',$keyword);
            });
        }
        if ($request->filled('mobile')) {
            $query->where('mobile', 'like', '%'.$request->mobile.'%');
        }
        if ($request->filled('username')) {
            $query->where('username', 'like', '%'.$request->username.'%');
        }
        if ($request->filled('uid')) {
            $query->where('uid', $request->uid);
        }
        if ($request->filled('status') && $request->status !== '') {
            $query->where('status', (int) $request->status);
        }
        if ($request->filled('category_id')) {
            $query->whereRaw("JSON_EXTRACT(information, '$.category_id') = ?", [$request->category_id]);
        }
        if ($request->filled('created_at')) {
            $query->whereDate('created_at', $request->created_at);
        }

        $paginator = $query->paginate($pageSize, ['*'], 'page', $page);

        $list = collect($paginator->items())->map(function ($app) {
            $info = $app->information ?? [];
            return [
                'id' => $app->id,
                'store_name' => $info['store_name'] ?? '未知门店',
                'applicant' => [
                    'name' => $app->member ? $app->member->nickname : ($app->realname ?: '未知联系人'),
                    'id' => $app->member ? $app->member->uid : $app->id,
                    'avatar' => $app->member && $app->member->avatar ? $app->member->avatar : '',
                ],
                'phone' => $app->mobile ?: '-',
                'realname' => $app->realname ?: '-',
                'address' => $app->full_address ?: '-',
                'category_name' => $app->category_name ?: '-',
                'status' => $this->getStatusLabel($app->status),
                'status_class' => $this->getStatusClass($app->status),
                'submitted_at' => $app->created_at ? $app->created_at->format('Y-m-d H:i') : '-',
                'reviewed_at' => $info['reviewed_at'] ?? null,
                'reason' => $info['review_comment'] ?? null,
            ];
        })->values();

        return response()->json([
            'status' => 'success',
            'data' => [
                'list' => $list,
                'pagination' => [
                    'page' => $paginator->currentPage(),
                    'pageSize' => $paginator->perPage(),
                    'total' => $paginator->total(),
                ],
            ],
        ]);
    }


    /**
     * 审核通过
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function approve(Request $request, $id)
    {
        try {
            // 1. 验证申请状态和用户名唯一性
            $application = StoreApply::findOrFail($id);
            
            if ($application->status != 0) {
                return response()->json([
                    'status' => 'error',
                    'message' => '该申请已经审核过了'
                ]);
            }
            
            // 验证用户名唯一性
            $existingUser = \DB::table('ims_yz_admin_users')->where('username', $application->username)->first();    
            if ($existingUser) {
                return response()->json([
                    'status' => 'error',
                    'message' => '该用户名已存在系统'
                ]);
            }

            $enableQuotaInput = $request->input('enable_quota', 1);
            $enableQuota = !in_array($enableQuotaInput, [0, '0', false, 'false'], true);
            $quotaAmount = $this->sanitizeQuotaAmount($request->input('quota_amount', 1000), 1000);
            
            // 使用事务保证一致性
            \DB::transaction(function () use ($application, $request, $enableQuota, $quotaAmount) {
                // 2. 注册系统用户账号
                $userUid = $this->registerSystemUser($application);
                if (!is_numeric($userUid)) {
                    throw new \Exception(is_string($userUid) ? $userUid : '用户注册失败');
                }

                // 3. 创建收银台商品记录
                $goodsModel = $this->createCashierGoods($application);

                // 4. 创建门店记录
                $storeId = $this->createStore($userUid, $application, $goodsModel);

                // 5. 设置门店默认配置
                $this->setStoreDefaultSettings($storeId);

                // 6. 处理提成比例设置
                $this->handleCommissionSettings($application, $goodsModel, $storeId);

                // 7. 初始化授信额度配置
                $this->initializeStoreQuota($application->uniacid ?? 1, $storeId, $enableQuota, $quotaAmount);

                // 8. 创建员工审核权限记录
                $this->createStaffAuth($application, $storeId);

                // 9. 更新申请状态为通过
                $this->updateApplicationStatus($application, $request);
            });

            // 10. 发送通知消息（事务外，不影响核心数据一致性）
            $this->sendNotification($application);
            
            return response()->json([
                'status' => 'success',
                'message' => '审核通过成功'
            ]);
            
        } catch (\Exception $e) {
            \Log::error('门店申请审核失败', [
                'application_id' => $id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'status' => 'error',
                'message' => '操作失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 审核拒绝
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function reject(Request $request, $id)
    {
        try {
            $application = StoreApply::findOrFail($id);
            
            if ($application->status != 0) {
                 return response()->json([
                     'status' => 'error',
                     'message' => '该申请已经审核过了'
                 ]);
             }
             
             $comment = $request->input('reason');
             if (empty($comment)) {
                 return response()->json([
                     'status' => 'error',
                     'message' => '拒绝理由不能为空'
                 ]);
             }
             
             // 更新information字段中的审核信息
             $info = $application->information ?? [];
             $info['review_comment'] = $comment;
             $info['reviewed_at'] = now()->format('Y-m-d H:i:s');
             $info['reviewer_id'] = auth()->id();
             
             $application->update([
                 'status' => 2,
                 'information' => $info,
                 'updated_at' => time()
             ]);

            return response()->json([
                'status' => 'success',
                'message' => '审核拒绝成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '操作失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取申请详情
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id)
    {
        try {
            $application = StoreApply::with('member')->findOrFail($id);
            $info = $application->information ?? [];
            
            // 查询省市区名称
            $provinceName = '';
            $cityName = '';
            $districtName = '';
            $fullAddress = '';
            
            if (isset($info['province_id']) && $info['province_id']) {
                $province = \App\Models\Address::find($info['province_id']);
                $provinceName = $province ? $province->areaname : '';
            }
            
            if (isset($info['city_id']) && $info['city_id']) {
                $city = \App\Models\Address::find($info['city_id']);
                $cityName = $city ? $city->areaname : '';
            }
            
            if (isset($info['district_id']) && $info['district_id']) {
                $district = \App\Models\Address::find($info['district_id']);
                $districtName = $district ? $district->areaname : '';
            }
            
            // 构建完整地址
            $fullAddress = $provinceName . $cityName . $districtName . ($info['address'] ?? '');
            
            // 查询门店分类名称
            $categoryName = '未填写';
            if (isset($info['category_id']) && $info['category_id']) {
                $category = \DB::table('ims_yz_store_category')->where('id', $info['category_id'])->first();
                $categoryName = $category ? $category->name : '未填写';
            }
            
            $detail = [
                'id' => $application->id,
                'uniacid' => $application->uniacid,
                'uid' => $application->uid,
                'username' => $application->username,
                'realname' => $application->realname,
                'mobile' => $application->mobile,
                'status' => $application->status,
                'status_text' => $this->getStatusLabel($application->status),
                'status_class' => $this->getStatusClass($application->status),
                'created_at' => $application->created_at ? $application->created_at->format('Y-m-d H:i:s') : '-',
                'updated_at' => $application->updated_at ? $application->updated_at->format('Y-m-d H:i:s') : '-',
                'order_id' => $application->order_id,
                'validity' => $application->validity,
                
                // 门店信息
                'store_name' => $info['store_name'] ?? '未填写',
                'store_address' => $fullAddress ?: '未填写',
                'store_phone' => $application->mobile ?? '未填写',
                'store_category' => $categoryName,
                'store_description' => $info['store_introduce'] ?? '未填写',
                'business_license' => $info['business_license'] ?? '未提供',
                'id_card_front' => $info['id_card_front'] ?? '未提供',
                'id_card_back' => $info['id_card_back'] ?? '未提供',
                'address' => $fullAddress ?: '未填写',
                'province_name' => $provinceName,
                'city_name' => $cityName,
                'district_name' => $districtName,
                
                // 申请人信息
                'applicant' => [
                    'name' => $application->member ? $application->member->nickname : ($application->realname ?: '未知联系人'),
                    'id' => $application->member ? $application->member->uid : $application->id,
                    'avatar' => $application->member && $application->member->avatar ? $application->member->avatar : '',
                ],
                
                // 审核信息
                'review_info' => [
                    'reviewed_at' => $info['reviewed_at'] ?? null,
                    'reviewer_id' => $info['reviewer_id'] ?? null,
                    'review_comment' => $info['review_comment'] ?? null,
                ],
                
                // 完整信息
                'information' => $info
            ];

            return response()->json([
                'status' => 'success',
                'data' => $detail
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取详情失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取省市区列表API
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAddresses(Request $request)
    {
        try {
            $level = $request->get('level', 1); // 1-省份，2-城市，3-区县
            $parentId = $request->get('parent_id'); // 父级ID
            
            $query = \App\Models\Address::where('level', $level);
            
            // 如果有父级ID，则添加条件
            if ($parentId) {
                $query->where('parentid', $parentId);
            }
            
            $addresses = $query->orderBy('id')
                ->get(['id', 'areaname'])
                ->map(function ($item) {
                    return [
                        'id' => $item->id,
                        'name' => $item->areaname
                    ];
                });
                
            return response()->json([
                'status' => 'success',
                'data' => $addresses
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取地址列表失败：' . $e->getMessage()
            ]);
        }
    }


    /**
     * 获取状态标签
     *
     * @param int $status
     * @return string
     */
    private function getStatusLabel($status)
    {
        switch ($status) {
            case 0:
                return '待审核';
            case 1:
                return '审核通过';
            case 2:
                return '审核拒绝';
            default:
                return '未知状态';
        }
    }

    /**
     * 获取状态样式类
     *
     * @param int $status
     * @return string
     */
    private function getStatusClass($status)
    {
        switch ($status) {
            case 0:
                return 'badge-warning';
            case 1:
                return 'badge-success';
            case 2:
                return 'badge-danger';
            default:
                return 'badge-secondary';
        }
    }

    /**
     * 注册系统用户账号
     *
     * @param StoreApply $application
     * @return int|string
     */
    private function registerSystemUser($application)
    {
        try {
            // 生成盐值
            $salt = $this->generateSalt();
            
            // 创建系统用户到 yz_admin_users 表
            $userId = \DB::table('ims_yz_admin_users')->insertGetId([
                'username' => $application->username,
                'password' => $application->password, // 原始密码，需要根据系统加密方式处理
                'salt' => $salt,
                'lastvisit' => time(),
                'lastip' => request()->ip(),
                'joinip' => request()->ip(),
                'status' => 2,
                'remark' => '门店管理员账号',
                'owner_uid' => 0,
                'created_at' => time(),
                'updated_at' => time(),
                'type' => 3,
            ]);
            
            \Log::info('门店账号注册成功', [
                'username' => $application->username,
                'user_id' => $userId
            ]);
            
            return $userId;
        } catch (\Exception $e) {
            \Log::error('门店账号注册失败', [
                'username' => $application->username,
                'error' => $e->getMessage()
            ]);
            return '用户注册失败：' . $e->getMessage();
        }
    }

    /**
     * 创建收银台商品记录
     *
     * @param StoreApply $application
     * @return \App\Models\Goods
     */
    private function createCashierGoods($application)
    {
        $info = $application->information ?? [];
        
        // 创建商品记录
        $goodsData = [
            'title' => $info['store_name'] ?? '门店收银台',
            'thumb' => $info['thumb'] ?? '',
            'description' => $info['store_introduce'] ?? '',
            'price' => 1.00, // 收银台商品固定价格
            'market_price' => 1.00,
            'cost_price' => 1.00,
            'stock' => 999999, // 无限库存
            'sku' => '个',
            'weight' => 0,
            'status' => 1, // 上架状态
            'is_deleted' => 0,
            'brand_id' => 0, // 设置品牌ID为0
            'is_new' => 0,
            'is_hot' => 0,
            'is_discount' => 0,
            'is_recommand' => 0,
            'display_order' => 0,
            'type' => 1,
            'is_plugin' => 0,
            'plugin_id' => 31, // 收银台插件ID
        ];
        
        $goods = \App\Models\Goods::create($goodsData);
        
        // 创建收银台商品配置
        $cashierGoods = new \App\Models\CashierGoods();
        $cashierGoods->goods_id = $goods->id;
        $cashierGoods->is_open = 1;
        $cashierGoods->shop_commission = $info['shop_commission'] ?? 0;
        $cashierGoods->settlement_day = 0;
        $cashierGoods->is_write_information = 0;
        $cashierGoods->is_cash_pay = 1;
        $cashierGoods->shop_award_point = 0;
        $cashierGoods->save();
        
        return $goods;
    }

    /**
     * 创建门店记录
     *
     * @param int $userUid
     * @param StoreApply $application
     * @param \App\Models\Goods $goodsModel
     * @return int
     */
    private function createStore($userUid, $application, $goodsModel)
    {
        $info = $application->information ?? [];
        
        // 计算有效期
        $validity = 0;
        if ($application->validity > 0) {
            $validity = $application->validity * 24 * 60 * 60 + time();
        }
        
        // 创建门店记录
        $store = new \App\Models\Store();
        $store->uniacid = $application->uniacid ?? 1;
        $store->uid = $application->uid;
        $store->user_uid = $userUid;
        $store->store_name = $info['store_name'] ?? '';
        $store->thumb = $info['thumb'] ?? '';
        $store->banner_thumb = $info['banner_thumb'] ?? '';
        $store->category_id = $info['category_id'] ?? 0;
        $store->province_id = $info['province_id'] ?? 0;
        $store->city_id = $info['city_id'] ?? 0;
        $store->district_id = $info['district_id'] ?? 0;
        $store->street_id = $info['street_id'] ?? 0;
        $store->address = $info['address'] ?? '';
        $store->longitude = $info['lng'] ?? '';
        $store->latitude = $info['lat'] ?? '';
        $store->mobile = $application->mobile;
        $store->store_introduce = $info['store_introduce'] ?? '';
        $store->cashier_id = $goodsModel->id;
        $store->aptitude_imgs = $info['aptitude_imgs'] ?? [];
        $store->id_card_imgs = $info['id_card_imgs'] ?? [];
        $store->other_imgs = $info['other_imgs'] ?? [];
        $store->information = $info['information_thumb'] ?? '';
        $store->business_hours_start = $info['business_hours_start'] ?? '';
        $store->business_hours_end = $info['business_hours_end'] ?? '';
        $store->dispatch_type = [2]; // 默认支持上门自提
        $store->validity = $validity;
        $store->validity_status = $validity ? 0 : 1;
        $store->is_black = 0;
        $store->is_hide = 0;
        $store->specify_show = 0;
        $store->operating_state = 1;
        $store->audio_open = 0;
        // 补齐必须字段默认值，避免非空字段无默认导致插入失败
        $store->platform_ids = '';
        $store->settlement_num = 0;
        $store->settlement_type = 0;
        $store->recruiter_id = 0;
        $store->platform_id = 0;
        $store->save();
        
        // 设置城市首字母
        if ($store->city_id) {
            $address = \App\Models\Address::find($store->city_id);
            if ($address) {
                $store->initials = $this->getFirstCharter($address->areaname);
                $store->save();
            }
        }
        
        return $store->id;
    }

    /**
     * 初始化门店授信额度
     *
     * @param int|null $uniacid
     * @param int $storeId
     * @param bool $enableQuota
     * @param float $quotaAmount
     * @return void
     */
    private function initializeStoreQuota($uniacid, $storeId, $enableQuota, $quotaAmount)
    {
        if (empty($storeId)) {
            return;
        }

        $now = time();
        $amount = $enableQuota ? max(0, round((float) $quotaAmount, 2)) : 0;

        $data = [
            'uniacid' => $uniacid ?: 1,
            'store_id' => $storeId,
            'num' => $amount,
            'stock_num' => 0,
            'status' => 0,
            'stock_status' => 0,
            'switch' => 0,
            'updated_at' => $now,
        ];

        $exists = \DB::table('ims_hhm_coin_corp_quota')
            ->where('store_id', $storeId)
            ->first();

        if ($exists) {
            \DB::table('ims_hhm_coin_corp_quota')
                ->where('store_id', $storeId)
                ->update($data);
        } else {
            $data['created_at'] = $now;
            \DB::table('ims_hhm_coin_corp_quota')->insert($data);
        }
    }

    /**
     * 设置门店默认配置
     *
     * @param int $storeId
     */
    private function setStoreDefaultSettings($storeId)
    {
        $defaultSettings = [
            'store' => [
                'shop_commission' => 0,
                'settlement_day' => 0
            ],
            'point' => [
                'set' => [
                    "money_max" => 0,
                    "give_point" => 0,
                    "shop_award_point" => 0
                ]
            ],
            'love' => [
                'deduction' => 1,
                'deduction_proportion' => 0,
                'award' => 1,
                'award_proportion' => 0,
                'award_shop' => 0
            ],
            'discount' => [
                'discount_method' => 1,
                'discount_value' => []
            ],
            'commission' => [
                'is_commission' => 1,
                'hascommission' => 1,
                'level' => 3,
                'first_level' => 0,
                'second_level' => 0,
                'third_level' => 0,
                'rule' => []
            ],
            'team-dividend' => [
                'is_dividend' => 1,
                'has_dividend' => 1,
                'has_dividend_rate' => 0
            ],
            'area-dividend' => [
                'is_dividend' => 1,
                'has_dividend' => 1,
                'has_dividend_rate' => 0
            ],
            'merchant' => [
                'is_open_bonus_staff' => 1,
                'is_open_bonus_center' => 1,
                'staff_bonus' => 0
            ],
            'single-return' => [
                'is_single_return' => 1,
                'return_rate' => 0
            ],
            'full-return' => [
                'is_open' => 0
            ]
        ];
        
        foreach ($defaultSettings as $key => $value) {
            \App\Models\StoreSetting::create([
                'store_id' => $storeId,
                'key' => $key,
                'value' => $value
            ]);
        }
    }

    /**
     * 处理提成比例设置
     *
     * @param StoreApply $application
     * @param \App\Models\Goods $goodsModel
     * @param int $storeId
     */
    private function handleCommissionSettings($application, $goodsModel, $storeId)
    {
        $info = $application->information ?? [];
        
        // 如果申请时设置了平台提成比例
        if (isset($info['shop_commission']) && $info['shop_commission'] > 0) {
            // 更新门店设置
            $storeSetting = \App\Models\StoreSetting::where('store_id', $storeId)
                ->where('key', 'store')
                ->first();
            
            if ($storeSetting) {
                $value = $storeSetting->value;
                $value['shop_commission'] = $info['shop_commission'];
                $storeSetting->value = $value;
                $storeSetting->save();
            }
            
            // 更新收银台商品设置
            \App\Models\CashierGoods::where('goods_id', $goodsModel->id)
                ->update(['shop_commission' => $info['shop_commission']]);
        }
    }

    /**
     * 创建员工审核权限记录
     *
     * @param StoreApply $application
     * @param int $storeId
     */
    private function createStaffAuth($application, $storeId)
    {
        try {
            $currentTime = time();
            $operateId = auth()->id() ?? 0; // 当前操作人ID（审核人）
            
            // 插入员工审核权限记录
            \DB::table('ims_hhm_staff_auth')->insert([
                'uid' => $application->uid, // 店长用户ID
                'store_id' => $storeId, // 门店ID
                'status' => 10, // 已授权
                'operate_id' => $operateId, // 操作人ID
                'created_at' => $currentTime,
                'updated_at' => $currentTime,
                'deleted_at' => null
            ]);
            
            \Log::info('员工审核权限记录创建成功', [
                'uid' => $application->uid,
                'store_id' => $storeId,
                'operate_id' => $operateId
            ]);
        } catch (\Exception $e) {
            \Log::error('员工审核权限记录创建失败', [
                'uid' => $application->uid,
                'store_id' => $storeId,
                'error' => $e->getMessage()
            ]);
            throw $e;
        }
    }

    /**
     * 更新申请状态为通过
     *
     * @param StoreApply $application
     * @param Request $request
     */
    private function updateApplicationStatus($application, $request)
    {
        $info = $application->information ?? [];
        $info['review_comment'] = $request->input('comment', '');
        $info['reviewed_at'] = now()->format('Y-m-d H:i:s');
        $info['reviewer_id'] = auth()->id();
        
        $application->update([
            'status' => 1,
            'information' => $info,
            'updated_at' => time()
        ]);
    }

    /**
     * 发送通知消息
     *
     * @param StoreApply $application
     */
    private function sendNotification($application)
    {
        // 这里可以集成消息通知服务
        // 比如发送短信、微信模板消息等
        \Log::info('门店申请审核通过通知', [
            'application_id' => $application->id,
            'uid' => $application->uid,
            'store_name' => $application->information['store_name'] ?? ''
        ]);
    }

    /**
     * 规范化授信额度金额
     *
     * @param mixed $value
     * @param float $default
     * @return float
     */
    private function sanitizeQuotaAmount($value, $default = 1000.00)
    {
        if ($value === null || $value === '') {
            return round((float) $default, 2);
        }

        if (is_numeric($value)) {
            return max(0, round((float) $value, 2));
        }

        if (is_string($value)) {
            $filtered = preg_replace('/[^\d.]/', '', $value);
            if ($filtered === '') {
                return round((float) $default, 2);
            }
            return max(0, round((float) $filtered, 2));
        }

        return max(0, round((float) $default, 2));
    }

    /**
     * 将中文转换为 Unicode 转义，兼容 JSON 文本匹配
     *
     * @param string $value
     * @return string
     */
    private function convertToUnicodeEscape($value)
    {
        if ($value === null || $value === '') {
            return '';
        }

        $chars = preg_split('//u', $value, -1, PREG_SPLIT_NO_EMPTY);
        $unicode = '';
        foreach ($chars as $char) {
            $bin = iconv('UTF-8', 'UCS-2BE', $char);
            if ($bin === false) {
                continue;
            }
            $unicode .= '\\u' . strtoupper(bin2hex($bin));
        }
        return $unicode;
    }

    /**
     * 获取中文首字母
     *
     * @param string $str
     * @return string
     */
    private function getFirstCharter($str)
    {
        if (empty($str)) {
            return '';
        }

        $fchar = ord($str[0]);

        if ($fchar >= ord('A') && $fchar <= ord('z')) {
            return strtoupper($str[0]);
        }

        $s1 = iconv('UTF-8', 'gb2312', $str);
        $s2 = iconv('gb2312', 'UTF-8', $s1);
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;

        if ($asc >= -20319 && $asc <= -20284) return 'A';
        if ($asc >= -20283 && $asc <= -19776) return 'B';
        if ($asc >= -19775 && $asc <= -19219) return 'C';
        if ($asc >= -19218 && $asc <= -18711) return 'D';
        if ($asc >= -18710 && $asc <= -18527) return 'E';
        if ($asc >= -18526 && $asc <= -18240) return 'F';
        if ($asc >= -18239 && $asc <= -17923) return 'G';
        if ($asc >= -17922 && $asc <= -17418) return 'H';
        if ($asc >= -17417 && $asc <= -16475) return 'J';
        if ($asc >= -16474 && $asc <= -16213) return 'K';
        if ($asc >= -16212 && $asc <= -15641) return 'L';
        if ($asc >= -15640 && $asc <= -15166) return 'M';
        if ($asc >= -15165 && $asc <= -14923) return 'N';
        if ($asc >= -14922 && $asc <= -14915) return 'O';
        if ($asc >= -14914 && $asc <= -14631) return 'P';
        if ($asc >= -14630 && $asc <= -14150) return 'Q';
        if ($asc >= -14149 && $asc <= -14091) return 'R';
        if ($asc >= -14090 && $asc <= -13319) return 'S';
        if ($asc >= -13318 && $asc <= -12839) return 'T';
        if ($asc >= -12838 && $asc <= -12557) return 'W';
        if ($asc >= -12556 && $asc <= -11848) return 'X';
        if ($asc >= -11847 && $asc <= -11056) return 'Y';
        if ($asc >= -11055 && $asc <= -10247) return 'Z';
        if ('衢州市' === $str) return 'Q';

        return '';
    }

    /**
     * 生成随机盐值
     *
     * @param int $length
     * @return string
     */
    private function generateSalt($length = 8)
    {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, 35);
        $seed = $seed . 'zZ' . strtoupper($seed);
        $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
        $length--;
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed[mt_rand(0, $max)];
        }
        return $hash;
    }
}